package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.adapter.ImagePagerAdapter;
import com.movecar.listview.MyListView;
import com.movecar.model.GetGroupBean.UserDetail;
import com.movecar.model.GroupBean;
import com.movecar.model.Pictures;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.ListUtils;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 查看参加用户信息
 * 
 * @author Zhao.JQ
 * 
 */
public class GroupJoinedActivity extends Activity implements OnClickListener, OnItemClickListener {

	private String messageId = "";
	private MyListView mListView;
	private ArrayList<UserDetail> usersData = new ArrayList<UserDetail>();
	private CustomProgressDialog progressDialog = null;
	private ImageLoader imageLoader = null;
	private LinearLayout main_linear, list_linear;
	private RelativeLayout  listview_title;
	private TextView group_name;
	private AutoScrollViewPager group_img;

	private List<Pictures> pictureList;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_joined_people);
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		Intent intent = getIntent();
		String name = intent.getStringExtra("group_name");
		String img = intent.getStringExtra("group_img");

		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		mListView = (MyListView) findViewById(R.id.mListView);
		mListView.setOnItemClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText(getIntent().getStringExtra("JoinNum"));
		list_linear = (LinearLayout) findViewById(R.id.list_linear);
		main_linear = (LinearLayout) findViewById(R.id.main_linear);
		listview_title = (RelativeLayout) findViewById(R.id.listview_title);
		group_name = (TextView) findViewById(R.id.group_name);
		group_img = (AutoScrollViewPager) findViewById(R.id.group_img);
		// 字体加粗
		// 活动名称
		TextPaint tp = group_name.getPaint();
		tp.setFakeBoldText(true);
		group_name.setText(name);
		// 活动图片
		if (!"".equals(img) && null != img) {
			group_img.setVisibility(View.VISIBLE);
			Type t = new TypeToken<List<Pictures>>() {
			}.getType();
			Gson g = new Gson();

			try {
				pictureList = g.fromJson(img, t);
			} catch (Exception e) {
				return;
			}
			group_img.setAdapter(new ImagePagerAdapter(GroupJoinedActivity.this, pictureList).setInfiniteLoop(false));

			group_img.setInterval(2000);
			group_img.startAutoScroll();
			group_img.setCycle(true);
			group_img.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % ListUtils.getSize(pictureList));

		}

		if (this.getIntent() != null) {
			messageId = getIntent().getStringExtra("messageId");
			jsonData();

		}

	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;

		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void jsonData() {

		startProgressDialog();
		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "querySigninNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("messageId", messageId));
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Type type = new TypeToken<List<UserDetail>>() {
				}.getType();
				Gson gson = new Gson();
				stopProgressDialog();
				try {
					usersData = gson.fromJson(result, type);
				} catch (Exception e) {
					return;
				}

				if (usersData == null) {
					Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
					return;
				} else {
					main_linear.setVisibility(View.VISIBLE);
					if (usersData.size() != 0) {
						listview_title.setVisibility(View.VISIBLE);
					}
					list_linear.setVisibility(View.VISIBLE);
					mListView.setVisibility(View.VISIBLE);
					if (usersData.size() != 0) {
						DataAdapter dataAdapter = new DataAdapter(GroupJoinedActivity.this, usersData);
						mListView.setAdapter(dataAdapter);

					}

				}

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(GroupJoinedActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	class DataAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;
		private ArrayList<UserDetail> usersData;

		DataAdapter(Activity activity, ArrayList<UserDetail> usersData) {

			this.usersData = usersData;
			inflater = LayoutInflater.from(activity);
		}

		@Override
		public int getCount() {

			return usersData.size();
		}

		@Override
		public Object getItem(int arg0) {

			return usersData.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.joined_people_item, null);
				viewHolder.friend_tag = (ImageView) view.findViewById(R.id.friend_tag);
				viewHolder.userNickName = (TextView) view.findViewById(R.id.userName);
				viewHolder.icon = (ImageView) view.findViewById(R.id.userImg);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			if ("1".equals(usersData.get(position).getFriendFlag())) {
				viewHolder.friend_tag.setVisibility(View.VISIBLE);
			}

			String nickName = usersData.get(position).getNickname();

			viewHolder.userNickName.setText(nickName);

			if (usersData.get(position).getIcon().contains("default")) {
				imageLoader.displayImage(AppConfig.HOST + usersData.get(position).getIcon(), viewHolder.icon,
						Constants.image_display_options);
			} else {
				imageLoader.displayImage(AppConfig.HOST + usersData.get(position).getIcon(), viewHolder.icon,
						Constants.image_display_options_conner);
			}

			return view;
		}

		class ViewHolder {

			TextView userNickName;
			ImageView icon, friend_tag;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		if (!usersData.get(position).getUserId().equals(DataStore.getInstance().getUserId())) {
			Intent intent = new Intent().setClass(this, FriendPersonalInfActivity.class);
			intent.putExtra("shareUserId", usersData.get(position).getUserId());
			startActivity(intent);
		} else {

			Intent intent = new Intent().setClass(this, PersonalInfActivity.class);
			startActivity(intent);

		}

	}
}
